package com.hejiale.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hejiale.lease.model.entity.BrowsingHistory;
import com.hejiale.lease.web.app.mapper.BrowsingHistoryMapper;
import com.hejiale.lease.web.app.service.BrowsingHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hejiale.lease.web.app.vo.history.HistoryItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author hejiale
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    /**
     * 分页查询浏览历史
     * @param page
     * @param userId
     * @return
     */
    @Override
    public IPage<HistoryItemVo> pageItemByUserId(IPage<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.pageItemByUserId(page,userId);
    }

    /**
     * 保存浏览历史
     * @param userId
     * @param id
     */
    @Override
    public void saveHistory(Long userId, Long id) {
        // System.out.println("保存浏览记录： "+Thread.currentThread().getName());
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getUserId, userId);
        queryWrapper.eq(BrowsingHistory::getRoomId, id);

        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);

        // 如果存在，更新浏览时间
        if (browsingHistory != null){
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.updateById(browsingHistory);
        }else {
            browsingHistory = new BrowsingHistory(userId,id,new Date());
            browsingHistoryMapper.insert(browsingHistory);
        }
    }
}